package com.nononsenseapps.feeder.sync.local.source.email

import android.content.Context
import androidx.core.net.toUri
import com.nononsenseapps.feeder.db.DEFAULT
import com.nononsenseapps.feeder.parser.Author
import com.nononsenseapps.feeder.parser.Feed
import com.nononsenseapps.feeder.parser.Item
import org.joda.time.LocalDateTime
import timber.log.Timber
import java.util.*

object EmailSource_K9 {
    const val EMAIL_K9_Permission_READ="com.fsck.k9.permission.READ_MESSAGES"

    const val EMAIL_K9_PATH="/context/email/"

    val EMAIL_K9_URI="content://com.fsck.k9.messagenopermissionprovider".toUri()

    suspend fun fetchFeedForEmailK9(feedSql: com.nononsenseapps.feeder.db.entity.Feed,
                                    senderName:String,
                                    context: Context
    ): Feed?{
        var builderFeed: Feed?=null
        val feedItems= mutableListOf<Item>()

        val projection = arrayOf(
            MessageColumns._ID,
            MessageColumns.SEND_DATE,
            MessageColumns.SENDER_ADDRESS,
            MessageColumns.SENDER,
            MessageColumns.SUBJECT,

            MessageColumns.PREVIEW,
            MessageColumns.ACCOUNT,
            MessageColumns.ACCOUNT_NUMBER,
            MessageColumns.HAS_ATTACHMENTS,
            MessageColumns.UNREAD,
            MessageColumns.URI
        )
        val selection =if(senderName.isNullOrEmpty()) null else senderName
        val feedUrl= buildUrl(senderName)
        try{

            val cur = context.contentResolver.query(EMAIL_K9_URI, projection, senderName,null, null)

            Timber.d("read email:${EMAIL_K9_URI} filter:$selection cols:${cur?.columnNames?.joinToString()}")

            if (cur != null) {
                if (cur.moveToFirst()) {

                    do {
                        val id = cur.getString(cur.getColumnIndex(MessageColumns._ID))
                        val longDate = cur.getLong(cur.getColumnIndex(MessageColumns.SEND_DATE))
                        val sender = cur.getString(cur.getColumnIndex(MessageColumns.SENDER))
                        val senderAddress = cur.getString(cur.getColumnIndex(MessageColumns.SENDER_ADDRESS))
                        val subject = cur.getString(cur.getColumnIndex(MessageColumns.SUBJECT))

                        val preview = cur.getString(cur.getColumnIndex(MessageColumns.PREVIEW))
                        val account = cur.getString(cur.getColumnIndex(MessageColumns.ACCOUNT))
                        val accountNumber = cur.getString(cur.getColumnIndex(MessageColumns.ACCOUNT_NUMBER))
                        val hasAttachment = cur.getString(cur.getColumnIndex(MessageColumns.HAS_ATTACHMENTS))
                        val unRead = cur.getString(cur.getColumnIndex(MessageColumns.UNREAD))

                        val sendDate = LocalDateTime.fromDateFields(Date(longDate)).toString()

                        Timber.d("read email id:$id\t" +
                                "date:$sendDate\t"+
                                "sender:$sender\t" +
                                "senderAddress:$senderAddress\t" +
                                "subject:$subject\t"+

                                "account:$account\t"+
                                "accountNumber:$accountNumber\t"+

                                "hasAttachment:$hasAttachment\t"+
                                "unRead:$unRead\t" +

                                "preview:$preview\t" +
                                ""
                                )
                        val itemUrl = "$feedUrl&id=$id"

                        feedItems.add(
                            Item(
                            id=id,
                            title = subject,
                            url= itemUrl,
                            content_html=preview,
                            author = Author(account),
                            date_published=sendDate,
                            date_modified =sendDate,
                        )
                        )

                    } while (cur.moveToNext())

                    if (!cur.isClosed) {
                        cur.close()
                    }
                }
            }
            builderFeed = Feed(
                title=senderName,
                feed_url=feedUrl,
                items=feedItems,
                responseHash = UUID.randomUUID().hashCode()
            )
        }catch (e:Exception){
            Timber.d("read email exception:$e")
        }

        return builderFeed
    }

    fun buildUrl(senderName: String)= DEFAULT.SOURCE_URL+EMAIL_K9_PATH+"?"+senderName

}

object MessageColumns{
    /**
     * The unique ID for a row.
     *
     *
     * Type: INTEGER (long)
     */
    // @Column(Cursor.FIELD_TYPE_INTEGER)
    val _ID = "_id"

    /**
     * The count of rows in a directory.
     *
     *
     * Type: INTEGER
     */
    // @Column(Cursor.FIELD_TYPE_INTEGER)
    val _COUNT = "_count"

        /**
         * The number of milliseconds since Jan. 1, 1970, midnight GMT.
         *
         * <P>Type: INTEGER (long)</P>
         */
         val SEND_DATE = "date"

        /**
         * <P>Type: TEXT</P>
         */
         val SENDER = "sender"

        /**
         * <P>Type: TEXT</P>
         */
         val SENDER_ADDRESS = "senderAddress"

        /**
         * <P>Type: TEXT</P>
         */
         val SUBJECT = "subject"

        /**
         * <P>Type: TEXT</P>
         */
         val PREVIEW = "preview"

        /**
         * <P>Type: BOOLEAN</P>
         */
         val UNREAD = "unread"

        /**
         * <P>Type: TEXT</P>
         */
         val ACCOUNT = "account"

        /**
         * <P>Type: INTEGER</P>
         */
         val ACCOUNT_NUMBER = "accountNumber"

        /**
         * <P>Type: BOOLEAN</P>
         */
         val HAS_ATTACHMENTS = "hasAttachments"

        /**
         * <P>Type: BOOLEAN</P>
         */
         val HAS_STAR = "hasStar"

        /**
         * <P>Type: INTEGER</P>
         */
         val ACCOUNT_COLOR = "accountColor"
         val URI = "uri"
         val DELETE_URI = "delUri"

        @Deprecated("the field value is misnamed/misleading - present for compatibility purpose only. To be removed.")
        val INCREMENT = "id"

}

object AccountColumns {

        /**
         * <P>Type: INTEGER</P>
         */
        const val ACCOUNT_NUMBER = "accountNumber"

        /**
         * <P>Type: String</P>
         */
        const val ACCOUNT_NAME = "accountName"
        const val ACCOUNT_UUID = "accountUuid"
        const val ACCOUNT_COLOR = "accountColor"

}

object UnreadColumns {

        /**
         * <P>Type: String</P>
         */
        const val ACCOUNT_NAME = "accountName"

        /**
         * <P>Type: INTEGER</P>
         */
        const val UNREAD = "unread"

}